from fastapi import FastAPI, Request,Query
import uvicorn, json, datetime
# from tqdm import tqdm, trange

import torch
from transformers import BertTokenizer,BertForSequenceClassification
import pandas as pd
import numpy as np
import requests
import schedule
import datetime
from api import api_getAiTopic,api_getMessageList,api_updateaitopic,api_updateEmotion
import re
import time
from utils import logtime
# from 
twoModel=torch.load('./models/topic/sec_bert_topic.bin')
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
twoModel.to(device)
tokenizer=BertTokenizer.from_pretrained('./models/bert-base-chinese')

from loader import TopicBinaryClassification,PaddOrcModel
topicModel=TopicBinaryClassification()
orc=PaddOrcModel()

def api_setTopicAi(input,type='wechat'):
        logtime()
        if type=='wechat':
            res=api_getAiTopic(input)
            res =json.loads(res)
            answer={
                "msg":"匹配成功",
                "success":0,
                "fail":0,
                "text":0,
                "image":0,
                "total":0,
                "emtion":0,
                "emtionfail":0,
            }
        
            if res['success'] != True:
                raise res['msg']
            else:
                count=len(res['result']['list'])
                answer['total']=count
                out=[]
                for index,item in enumerate(res['result']['list']):
                    if index % 10 == index:
                        print(index+1,count)
                        print(f'当前进度为-----{((index+1)/count)*100}')
                    type=item['type']
                    args={'id':item['id']}
                    status=item['status']
                    if status !=0 :
                        continue
                    text=''
                    if type == 10:
                        answer['image']+=1
                        link=item['image']
                        text=orc.orcImg(link)
                        if len(text) ==0 or text is None:
                            print('-----------none-----------')
                        else:
                            args['text']=text
                        print( text)
                    else:
                        answer['text']+=1
                        text=item['text']
                    predicted,probabilite=topicModel.topciTest(text=text)
                    args['status']=1 if predicted ==0 else 2
                    args['probably']=int(probabilite.item()*100)
                    args['text']=text
                    updateRes= api_updateaitopic(args)
                    if item['source']=='xiaoji':
                        emotionRes=api_updateEmotion(args)
                        if emotionRes['success'] != True:
                            answer['emtionfail']+=1
                            continue
                        answer['emtion']+=1
                    if updateRes['success'] != True:
                        answer['topicfail']+=1
                        continue
                    answer['success']+=1
                    out.append(args)
        elif type=='xiaoji':
            api_getMessageList('2022-05-10')
        print(answer)
        return answer
app = FastAPI()

@app.get("/")
async def Predicting_response_test(request:Request):
    json_post_raw = await request.json()
    json_post = json.dumps(json_post_raw)
    json_post_list = json.loads(json_post)
    print(json_post_list)
    answer={
        "response": "ok",
        "status": 200,
    }
    return answer
@app.get('/predictingresponse')
async def Predicting_response(q: str = Query(None, title="Query string", description="Query string for the items to search in the database")):
    # print(q)
    # json_post_raw = await request.json()
    # json_post = json.dumps(json_post_raw)
    # json_post_list = json.loads(json_post)
    # text=json_post_list['text']
    print(q)
    result,probabilities=topicModel.topciTest(q)
    result='话题' if result==0 else '非话题'
    answer=f'<h1>{q}是{result}<br> 概率为{round(probabilities.item(),2)}</h1>'
    # {
    #      "response": "ok",
    #     "status": 200,
    #     '结果':'话题' if result==0 else '非话题',
    #     "概率":round(probabilities.item(),2)
    # }
    return answer

if __name__ == '__main__':
    try:
        schedule.every(1).minutes.do(api_setTopicAi, input={"page":1,"pageSize":1000,"status":0})
        while True:
            schedule.run_pending()    
            time.sleep(1)
    except BaseException as e:
        print(f'运行出错---error---:{e}')
    # uvicorn.run(app, host='0.0.0.0', port=7860, workers=1)
#     current_time = datetime.datetime.now()
# # 将日期和时间格式化为字符串
#     formatted_time = current_time.strftime("%Y-%m-%d")
#     messages=api_getMessageList('2023-07-01',formatted_time,pageSize=100000,type='99')
#     print(len(messages))
#     for index,item in enumerate(messages):
#         text=item['content']
#         input={
#             "type":9 if item['type']=='1' else 10,
#             "text":item['content'],
#             "source":'xiaoji',
#             "group_id":item['chat_id'],
#             "group_name":item['chat_id']
#         }
#         if item['type']=='2':
#             input['image']=text
#             text=orcImg(item['content'])
#         predicted,probabilite=topciTest(text=text)
#         if predicted ==0 and probabilite>0.8 :
#             res=api_createTopicAi(input)
#             if res['success'] ==False:
#                 print(res)
     

    

